package com.example.weatherapp1.workmanager

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.example.weatherapp1.data.repository.WeatherRepository
import com.example.weatherapp1.domain.service.WeatherService
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject


class WeatherUpdateWorker @Inject constructor(
    @ApplicationContext context: Context,
    params: WorkerParameters,
    private val weatherRepository: WeatherRepository,
    private val weatherService: WeatherService
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        return try {
            // 获取所有城市
            val cities = weatherRepository.getAllCities().value ?: emptyList()

            // 为每个城市更新天气
            for (city in cities) {
                weatherService.fetchAndSaveWeather(city)
            }

            Result.success()
        } catch (e: Exception) {
            e.printStackTrace()
            if (runAttemptCount < 3) {
                // 重试最多3次
                Result.retry()
            } else {
                Result.failure()
            }
        }
    }
}
